<template>
	<view class="contont">
		<nav-bar :title="pageInfo.navbarTitle" :iconLeft="true" />
		<view class="step">
			<uni-steps :options="stepData.step_list" active-icon="circle-filled" :active="stepData.step_active" />
		</view>
		<view class="step_zhanwei" />
		<view v-show="stepData.step_active == 0">
			<uni-forms :model="formData1" :rules="rules" ref="form_1" label-width="100px" validate-trigger="blur">
				<view class="content-bgc">
					<view class="b-con">
						<uni-forms-item label="物料编号" name="code" required>
							<view style="display: flex;gap:20rpx">
								<uni-easyinput v-model="formData1.code" placeholder="请输入产品编号" class="iptBor" :inputBorder="false"
									:disabled="switchCode" />
								<view style="margin-left: 20rpx" v-show="pageInfo.type == 'add'">
									<u-switch v-model="switchCode" @change="switchChange" size="20" />
									自动生成
								</view>
							</view>
						</uni-forms-item>
						<uni-forms-item label="物料名称" name="name" required>
							<uni-easyinput v-model="formData1.name" placeholder="请输入物料名称" class="iptBor" :inputBorder="false" />
						</uni-forms-item>
						<uni-forms-item label="货品分类" name="classify" required>
							<uni-data-select v-model="formData1.classify" :localdata="classify_list" placeholder="请选择货品分类"
								mode="underline" :clear="false" @close="blur('classify')" />
						</uni-forms-item>
						<uni-forms-item label="基本单位（小单位）" name="unit_main" required>
							<uni-data-select v-model="formData1.unit_main" :localdata="unit_list" placeholder="请选择基本单位"
								mode="underline" :clear="false" @close="blur('unit_main')" />
						</uni-forms-item>
						<uni-forms-item label="基本单位销售单价(元)" name="unit_main_price" required>
							<uni-easyinput v-model="formData1.unit_main_price" placeholder="请输入基本单位销售单价" class="iptBor"
								:inputBorder="false" />
						</uni-forms-item>
						<uni-forms-item label="副单位1">
							<uni-data-select v-model="formData1.unit_assist_one" :localdata="unit_list" placeholder="请选择基本副单位1"
								mode="underline" />
							<view class="hint-text">比基本单位大的单位，如：基本单位使用‘克’，那么副单位1可以使用‘千克’或者更大的单位</view>
						</uni-forms-item>
						<uni-forms-item label="副单位1与基本单位对应比例" name="unit_assist_one_ratio">
							<uni-easyinput v-model="formData1.unit_assist_one_ratio" placeholder="请输入单位1与基本单位对应比例" class="iptBor"
								:inputBorder="false" />
							<view class="hint-text">和基本单位的换算比例，如：1千克=1000克，这里填写：1000</view>
						</uni-forms-item>
						<uni-forms-item label="副单位1销售单价(元)" name="unit_assist_one_price">
							<uni-easyinput v-model="formData1.unit_assist_one_price" placeholder="请输入副单位1销售单价" class="iptBor"
								:inputBorder="false" />
							<view class="hint-text">副单位1对应的销售单价(元)</view>
						</uni-forms-item>
						<uni-forms-item label="副单位2">
							<uni-data-select v-model="formData1.unit_assist_two" :localdata="unit_list" placeholder="请选择基本副单位2"
								mode="underline" />
							<view class="hint-text">比副单位1大的单位，如：副单位1使用‘千克’，那么副单位2可以使用‘吨’或者更大的单位</view>
						</uni-forms-item>
						<uni-forms-item label="副单位2与副单位1对应比例" name="unit_assist_two_ratio">
							<uni-easyinput v-model="formData1.unit_assist_two_ratio" placeholder="请输入副单位2与副单位1对应比例" class="iptBor"
								:inputBorder="false" />
							<view class="hint-text">和副单位1的换算比例，如：1吨=1000千克，这里填写：1000</view>
						</uni-forms-item>
						<uni-forms-item label="副单位2销售单价(元)" name="unit_assist_two_price">
							<uni-easyinput v-model="formData1.unit_assist_two_price" placeholder="请输入副单位2销售单价" class="iptBor"
								:inputBorder="false" />
							<view class="hint-text">副单位2对应的销售单价(元)</view>
						</uni-forms-item>
						<uni-forms-item label="物料规格">
							<up-textarea v-model="formData1.specification" placeholder="请输入物料规格" />
							<view class="hint-text">格式(规格名称:规格值)多个规格用英文豆类号隔开，示例 (尺码:L,颜色:蓝色)</view>
						</uni-forms-item>
						<uni-forms-item label="生产物料用量" name="num">
							<uni-easyinput v-model="formData1.num" type="number" placeholder="请输入生产物料用量" class="iptBor"
								:inputBorder="false" />
							<view class="hint-text">物料用量以(基本单位)计量</view>
						</uni-forms-item>
						<uni-forms-item label="损耗率(%)" name="loss">
							<uni-easyinput v-model="formData1.loss" type="number" placeholder="请输入损耗率" class="iptBor"
								:inputBorder="false" />
							<view class="hint-text">例如损耗率为10%请里填写10</view>
						</uni-forms-item>
						<uni-forms-item label="库存预警阈值" name="threshold">
							<uni-easyinput v-model="formData1.threshold" type="number" placeholder="库存预警阈值" class="iptBor"
								:inputBorder="false" />
							<view class="hint-text">库存量低于该值，将会进行缺货提醒</view>
						</uni-forms-item>
						<uni-forms-item label="备注">
							<uni-easyinput v-model="formData1.desc" type="textarea" placeholder="请输入备注" />
						</uni-forms-item>
						<uni-forms-item label="主视图">
							<uni-file-picker v-model="formData1.file_url" file-mediatype="image" file-extname="png,jpg,jpeg"
								@select="select" return-type="object" title="只能上传jpg/png/jpeg文件，且建议大小不超过500kb"></uni-file-picker>
						</uni-forms-item>
					</view>
				</view>
			</uni-forms>
		</view>
		<view v-show="stepData.step_active == 1">
			<uni-forms :model="formData2" ref="form_2" label-width="100px">
				<view class="content-bgc">
					<view class="b-con" style="padding-bottom: 0;">
						<uni-forms-item label="物料类型" name="style" required :rules="[{ required: true, errorMessage: '请选择物料类型' }]">
							<uni-data-select v-model="formData2.style" :localdata="bomStyle_list" placeholder="请选择物料类型"
								mode="underline" :clear="false" @close="blur_2('style')" :disabled="pageInfo.type == 'edit'" />
						</uni-forms-item>
					</view>
					<view class="vieFlex" v-if="formData2.style == 1">
						<view class="b-con" v-for="(domains, index) in formData2.domains" :key="index">
							<uni-forms-item label="供应商" :name="`domains[${index}].supplier_id`" required
								:rules="[{ required: true, errorMessage: '请选择供应商' }]">
								<uni-data-select v-model="domains.supplier_id" :localdata="supplier_list" placeholder="请选择供应商"
									mode="underline" :clear="false" @change="suppSelect($event, index)" />
							</uni-forms-item>
							<uni-forms-item label="联系方式">
								<uni-easyinput v-model="domains.phone" disabled class="iptBor" :inputBorder="false" />
							</uni-forms-item>
							<uni-forms-item label="主营业务">
								<uni-easyinput v-model="domains.business" disabled class="iptBor" :inputBorder="false" />
							</uni-forms-item>
							<uni-forms-item label="基本单位采购单价" :name="`domains[${index}].price`" required
								:rules="[{ required: true, errorMessage: '请填写采购单价' }]">
								<uni-easyinput type="number" v-model="domains.price" placeholder="请输入" class="iptBor"
									:inputBorder="false" />
							</uni-forms-item>
							<uni-forms-item label="备注">
								<uni-easyinput type="textarea" v-model="domains.desc" disabled />
							</uni-forms-item>
							<view class="btn-box" v-if="index > 0">
								<view style="margin-left: auto;">
									<u-button size="small" text="删 除" type="error" @click="actProc('del', index)"></u-button>
								</view>
							</view>
						</view>
					</view>
					<view class="vieFlex" v-if="formData2.style == 2 || formData2.style == 3">
						<view class="b-con" v-for="(process, index) in formData2.process_list" :key="index">
							<uni-forms-item label="工序名称" :name="`process_list[${index}].name`" required
								:rules="[{ required: true, errorMessage: '请输入工序名称' }]">
								<uni-easyinput v-model="process.name" placeholder="请输入工序名称" class="iptBor" :inputBorder="false" />
							</uni-forms-item>
							<uni-forms-item label="单次工价(元)">
								<u-number-box v-model="process.price" inputWidth="100" :min="0"></u-number-box>
							</uni-forms-item>
							<uni-forms-item label="单次完成时间(秒)">
								<u-number-box v-model="process.finish_m" inputWidth="100" :min="0" :integer="true"></u-number-box>
							</uni-forms-item>
							<uni-forms-item label="工序要求">
								<uni-easyinput type="textarea" v-model="process.require" placeholder="请输入工序要求" />
							</uni-forms-item>
							<uni-forms-item label="备注">
								<uni-easyinput type="textarea" v-model="process.desc" placeholder="请输入备注" />
							</uni-forms-item>
							<view class="btn-box" v-if="index > 0">
								<view style="margin-left: auto;">
									<u-button size="small" text="删 除" type="error" @click="actProc('del', index)"></u-button>
								</view>
							</view>
						</view>
					</view>
					<view class="btn-box" v-show="formData2.style">
						<view style="margin-left: auto;">
							<u-button size="small" text="新增" type="primary" @click="actProc('add')"></u-button>
						</view>
					</view>
				</view>
			</uni-forms>
		</view>
		<view class="btn-box" style="padding-bottom: env(safe-area-inset-bottom)">
			<view class="btn-flex" v-show="stepData.step_active !== 0">
				<u-button text="上一步" @click="stepChange('last')" />
			</view>
			<view class="btn-flex" v-show="stepData.step_active !== 1">
				<u-button type="primary" text="下一步" @click="stepChange('next')" />
			</view>
			<view class="btn-flex" v-show="stepData.step_active == 1">
				<u-button type="success" text="提交" @click="save" />
			</view>
		</view>
	</view>
</template>
<script setup>
import { reactive, ref } from 'vue';
import { onLoad } from '@dcloudio/uni-app'
import dabomApi from '../../../api/dataa/da_bom'
import { generateCode } from '@/utils/index.js';
import { BASE_URL } from '../../../common/request';

//页面标题
const pageInfo = reactive({
	navbarTitle: 'BOM物料',
	type: '',
	edit_id: null,
})

onLoad((option) => {
	get_classify_list()
	get_unit_list()
	get_supplier_list()
	pageInfo.type = option.type
	if (option.type == 'edit') {
		pageInfo.navbarTitle = `${pageInfo.navbarTitle}(修改)`
		get_detail(option.id)
		pageInfo.edit_id = option.id
	} else {
		pageInfo.navbarTitle = `${pageInfo.navbarTitle}(新增)`
		formData1.code = generateCode('PR')
	}
})

const bomStyle_list = [
	{ text: '采购件', value: 1 },
	{ text: '自制品(半成品)', value: 2 },
	{ text: '委外件(半成品)', value: 3 },
]

//自动生成按钮
function switchChange(v) {
	if (v) {
		formData1.code = generateCode('BM')
	}
};

const form_1 = ref(null);
const formData1 = reactive({
	code: '',
	name: '',
	unit_main: '',
	classify: null,
	unit_main_price: 0,
	unit_assist_one: '',
	unit_assist_one_ratio: 1,
	unit_assist_one_price: 0,
	unit_assist_two: '',
	unit_assist_two_ratio: 1,
	unit_assist_two_price: 0,
	specification: '',
	threshold: 1,
	num: 1,
	loss: 0,
	desc: '',
	file_url: {},
});
const switchCode = ref(true);
const rules = {
	code: { rules: [{ required: true, errorMessage: '请填写产品编号' }] },
	name: { rules: [{ required: true, errorMessage: '请输入产品名称' }] },
	classify: { rules: [{ required: true, type: 'number', errorMessage: '请选择货品分类' }] },
	unit_main: { rules: [{ required: true, errorMessage: '请填写基本单位' }] },
	unit_main_price: { rules: [{ required: true, errorMessage: '请输入' }, { validateFunction: positiveNum }] },
	unit_assist_one_ratio: { rules: [{ required: true, errorMessage: '请输入' }, { validateFunction: positiveNum }] },
	unit_assist_one_price: { rules: [{ required: true, errorMessage: '请输入' }, { validateFunction: positiveNum }] },
	unit_assist_two_ratio: { rules: [{ required: true, errorMessage: '请输入' }, { validateFunction: positiveNum }] },
	unit_assist_two_price: { rules: [{ required: true, errorMessage: '请输入' }, { validateFunction: positiveNum }] },
	num: { rules: [{ required: true }, { validateFunction: positiveNum }] },
	loss: { rules: [{ required: true }, { validateFunction: positiveNum }] },
	threshold: {
		rules: [{ required: false, type: 'number', errorMessage: '请输入' },
		{
			validateFunction: (rule, value, data, callback) => {
				const num = Number(value)
				if (!Number.isInteger(num)) callback('请输入整数');
				return true
			}
		}]
	}
};
//单个校验
function blur(field) {
	form_1.value.validateField([field]).then().catch(err => { })
}
//单个校验
function blur_2(field) {
	form_2.value.validateField([field]).then().catch(err => { })
}
//表单校验，
function positiveNum(rule, value, data, callback) {
	const num = /^([1-9]\d*|0)(\.\d{1,2})?$/.test(value);
	if (!num) callback('请输入正数，且最多保留两位小数');
	return true
}

//工序
const form_2 = ref(null);
const formData2 = reactive({
	style: '',
	process_list: [
		{
			name: '',
			price: '0',
			finish_m: '0',
			require: '',
			desc: '',
		}
	],
	domains: [
		{
			supplier_id: null,
			phone: '',
			business: '',
			desc: '',
			price: null
		}
	]
});
//添加、删除工序
function actProc(type, index) {
	if (type == 'add') {
		if (formData2.style == 1) {
			const obj = {
				supplier_id: null,
				phone: '',
				business: '',
				desc: '',
				price: null
			}
			formData2.domains.push(obj)
		}
		if (formData2.style == 2 || formData2.style == 3) {
			const obj = {
				name: '',
				price: '0',
				finish_m: '0',
				require: '',
				desc: '',
			}
			formData2.process_list.push(obj)
		}

	}
	if (type == 'del') {
		if (formData2.style == 1) {
			formData2.domains.splice(index, 1)
		}
		if (formData2.style == 2 || formData2.style == 3) {
			formData2.process_list.splice(index, 1)
		}
	}
};

const fields = Object.keys(formData1)
//详情
function get_detail(id) {
	dabomApi.bom_detail(id).then(res => {
		const record = uni.$lodash.pick(res, fields) //过滤表单需要的字段
		formData2.style = res.style
		record.file_url = {
			name: 'file.txt',
			extname: "txt",
			url: res.file_url,
		}
		Object.assign(formData1, record)
		if (res.style == 1) {
			formData2.domains = JSON.parse(res.supplier_info)
		}
		if (res.style == 2 || 3) {
			formData2.process_list = JSON.parse(res.process_info)
		}
	})
};

//步骤列表
const stepData = reactive({
	step_list: [{
		title: '基本资料'
	}, {
		title: '物料类型'
	}],
	step_active: 0,
})
function stepChange(sta) {
	if (sta == 'last') {
		stepData.step_active -= 1;
	}
	if (sta == 'next') {
		const formRef = [form_1, form_2][stepData.step_active]
		formRef.value.validate().then(() => {
			stepData.step_active += 1;
		}).catch((error) => {
			console.log(formData2)
			uni.$u.toast(error[0].errorMessage);
		})
	}
};

// 上传
const action = BASE_URL + '/file/';
const token = uni.getStorageSync("assecss_token");
function select({ tempFiles }) {
	uni.uploadFile({
		url: action, //仅为示例，非真实的接口地址
		filePath: tempFiles[0].path,
		name: 'file',
		header: {
			'Authorization': "JWT " + token
		},
		success: (files) => {
			const data = JSON.parse(files.data)
			formData1.file_url = {
				name: 'file.txt',
				extname: "txt",
				url: data.file,
			}
		},
		fail: (err) => {
			uni.$u.toast('上传图片失败')
		}
	});
};
//提交表单
function save() {
	form_2.value.validate().then(() => {
		const params = uni.$lodash.cloneDeep(formData1) // 深拷贝一份form表单
		params.file_url = params.file_url.url
		if (formData2.style == 1) {
			params.default_supplier_id = formData2.domains[0].supplier_id
			params.supplier = formData2.domains.map(item => item.supplier_id)
			params.supplier_info = JSON.stringify(formData2.domains)
		}
		if (formData2.style == 2 || formData2.style == 3) {
			params.process_info = JSON.stringify({ 'process_info': formData2.process_list })
		}
		if (pageInfo.type == 'add') {
			dabomApi.post_bom(params).then(res => {
				uni.$u.toast('添加成功')
				setTimeout(() => {
					backRefsh();
				}, 1000)
			})
		} else {
			//修改
			dabomApi.patch_bom(params, pageInfo.edit_id).then((res) => {
				uni.$u.toast('修改成功')
				setTimeout(() => {
					backRefsh();
				}, 1000)
			})
		}
	}).catch((error) => {
		uni.$u.toast(error[0].errorMessage);
	})

}

//供应商列表
const supplier_list = ref([])
let supplierL = []
function get_supplier_list() {
	dabomApi.get_supplier({ page: 1, page_size: 99999, if_open: 1 }).then(res => {
		supplier_list.value = res.results.map(v => ({
			text: v.name,
			value: v.id
		}))
		supplierL = res.results
	})
};
function suppSelect(e, index) {
	const obj = supplierL.find(k => k.id == e)
	if (obj) {
		const parm = {
			phone: obj.phone,
			business: obj.business,
			desc: obj.desc,
			price: 0,
		}
		Object.assign(formData2.domains[index], parm)
	}
};


//单位列表
const unit_list = ref([])
function get_unit_list() {
	dabomApi.get_unit({ page: 1, page_size: 99999, if_open: 1 }).then(res => {
		unit_list.value = res.results.map(v => ({
			text: v.name,
			value: v.name
		}))
	})
};

//产品分类列表
const classify_list = ref([])
function get_classify_list() {
	dabomApi.get_product_classify({ page: 1, page_size: 99999, if_open: 1 }).then(res => {
		classify_list.value = res.results.map(v => ({
			text: v.name,
			value: v.id
		}))
	})
};


//返回上一级并刷新上一级页面
function backRefsh() {
	uni.navigateBack({
		delta: 1, // 返回的页面层数，1 表示返回上一级
		success: () => {
			uni.$bus.useBusEmit('da_bom');
		}
	})
};
</script>

<style lang="scss" scoped>
.vieFlex {
	display: flex;
	flex-direction: column;
	gap: 40rpx;
}

.step {
	width: 100%;
	background-color: #fff;
	position: fixed;
	z-index: 10;
	padding: 10px 0;
	border-bottom: 1px solid #dadbde;
}

.step_zhanwei {
	height: 48px;
}

.btn_zhanwei {
	height: 46px;
}
</style>